<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

import("Applications.AlloMediaUser.Classes.Actions.ShopAction");
import("Classes.Util.HTTP.AuthenticationManager");
import("Classes.Factory.DAOFactory");
import("Plugins.Shop.Classes.Model.Order");

use \PsiFramework\Applications\AlloMediaUser\Classes\Actions\ShopAction;
use \PsiFramework\Classes\Util\HTTP\AuthenticationManager;
use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Plugins\Shop\Classes\Model\Order;
use \PsiFramework\Classes\Util\UI\ModuleManager;
use \PsiFramework\Classes\Util\UI\HTML;
use \PsiFramework\Classes\Util\UI\LanguageManager;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de l'index
 *
 * @package Actions.Pages
 */
class ShowProfileServicesAction extends ShopAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();
        
        $entries = $this->_templateManager->getParameter('entries');
        $quantities = $this->_response->getAttribute('quantities');
        $currencySymbol = $this->_response->getAttribute('Currency')->getSymbol();
        
        $languageManager = LanguageManager::getInstance();
        
        $servicesArray = array();
        
        $this->_response->setAttribute('alone', count($entries)==1);
        
        $index = 0;
        foreach ($entries as $entry) {
        	$profile = $entry->getCategory()->getProfile();
        	$profile->getParts();
        	$parts = $profile->sortParts();
        	$ok = true;
        
        	for ($i = 0 ; $i<count($parts); $i++) {
        		$part = $parts[$i] ;
        		$theme = $part->getTheme();
        		$price = $part->getPrice();
        
        		$responseIdDao = DAOFactory::getDAO('ResponseId');
        		$responseId = $responseIdDao->retrieveByEntryAndTheme($entry, $theme);
        		
        		if (!$part->isFree()) {
        		    
        		    $serviceArray = array();
        		    $serviceArray['responseId'] = $responseId;
        		    
        			$active = ($responseId->isActive())?'activeService':'nonActiveService';
        			$serviceArray['active'] = $active;
        			
                    $link
                        = HTML::link(
                    		$entry . ' - ' . $theme,
                    		'action=ShowTheme&entry_id='.$entry->getid().
                    		'&form_id='.$theme->getId().
                            '&category_id='.$entry->getCategory()->getId()
                        );
                    $serviceArray['link'] = $link;
        
                    $sites = $responseId->getEntry()->getCategory()->getSites();
                    $siteString = '';
                    if (!is_null($sites) && count($sites)>0) {
                        foreach ($sites as $site) {
                            $siteString .= $site->getSite()->getName().'<br/>';
                        }
                    }
                    $serviceArray['sites'] = $siteString;

                    $quantitiesArray = array();
                    $bSelected = true ;
                    foreach ($quantities as $q=>$qv) {
                        $subTotal = $price*$q;
                        $realSubTotal = $subTotal;
                        
                        $discount = $qv['discount'];
                        if (!is_null($discount)) {
                            if ($discount->isPercentage()) {
                                $realSubTotal = $subTotal*(1-($discount->getValue()/100));
                            } else {
                                $realSubTotal = $subTotal-$discount->getValue();
                            }
                        }
                        
                        $label  = $qv['label'];
                        $label .= ' - <strong>'.number_format($realSubTotal, 2, '.', ' ').$currencySymbol.'</strong>';
                        if ($subTotal != $realSubTotal) {
                            $label .= ' ('.$languageManager->getText('INSTEAD_OF').' '.number_format($subTotal, 2, '.', ' ').$currencySymbol.')';
                        }
                        
                        $quantitiesArray[$q] = $label;
                    }
                    $serviceArray['quantities'] = $quantitiesArray;
                    
                    $servicesArray[$index] = $serviceArray;
                    
                    $index++;
                }
            }
        }
        
        $orderedServicesArray = array();
        
        $inactive = false;
        $index = 0;
        while (count($servicesArray)>0) {
            while (count($servicesArray)>0) {
                $closestDate = null;
                $closestIndex = null;
                foreach ($servicesArray as $i=>$serviceArray) {
                    if ($serviceArray['responseId']->isPaid() || $inactive) {
                        $date = $serviceArray['responseId']->getExpirationDate();
                        if (is_null($closestDate)
                            || (!is_null($date) && $date->before($closestDate))
                        ) {
                            $closestDate = $date;
                            $closestIndex = $i;
                        }
                    }
                }
                
                if (!is_null($closestDate)) {
                    $orderedServicesArray[$index] = $servicesArray[$closestIndex];
                    unset($servicesArray[$closestIndex]);
                    $index++;
                } else {
                    break;
                }
            }
            if ($inactive) {
                break;
            }
            $inactive = true;
        }
        
        foreach ($servicesArray as $serviceArray) {
            $orderedServicesArray[$index] = $serviceArray;
            $index++;
        }
        
        
        $this->_response->setAttribute('entriesArray', $orderedServicesArray);
        
        $this->findForward('success');
    }
}
